package com.itheima.controller;


import com.itheima.domain.FilePojo;
import com.itheima.domain.User;
import com.itheima.service.FileService;
import com.itheima.until.Code;
import com.itheima.until.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @ResponseBody
    @RequestMapping("/save")
    public Result index(@RequestParam("file") MultipartFile[] files,HttpSession session) throws IOException {
        if(files == null){
            return new Result(201,null,"请不要上传空的文件");

        }

        User user = (User) session.getAttribute("user");
        if (user == null){
            return new Result(201,null,"你尚未登陆");
        }
        Integer uid = user.getUid();

        for (MultipartFile file : files) {
            //原始文件名
            String originalFilename = file.getOriginalFilename();

            //构造唯一文件名
            int index = originalFilename.lastIndexOf(".");
            String exname = originalFilename.substring(index);
            String newFilename = UUID.randomUUID().toString() + exname;

            String dir = session.getServletContext().getRealPath("/res/images/avatar");
//            String address = "E:\\file\\" + newFilename;
            String address = dir + newFilename;

            file.transferTo((new File(address)));

            FilePojo filePojo = new FilePojo(uid, originalFilename, address);
            fileService.save(filePojo);

        }
        return new Result(200,null);
    }

//    @RequestMapping("/files")
//    @ResponseBody
//    public Result getAllFiles() {
//        List<FilePojo> filePojoList = fileService.getAll();
//
//        Integer code = filePojoList != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = filePojoList != null ? "" : "数据查询失败，请重试！";
//        return new Result(code,filePojoList,msg);
//    }

    @RequestMapping("/downLoad")
    @ResponseBody
    public void downLoad(@RequestParam("fid") int fid, HttpServletResponse response) throws IOException {
        try {
            FilePojo filePojo = fileService.getById(fid);
            String fileaddress = filePojo.getFileaddress();
            String filename = filePojo.getFilename();

            File file=new File(fileaddress);

            InputStream in = new BufferedInputStream(new FileInputStream(fileaddress));
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            in.close();

            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setHeader("Content-Length", file.length() + "");
            OutputStream output = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            output.write(buffer);
            output.flush();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/files")
    @ResponseBody
    public Result getAllFiles(HttpServletRequest request) {
        String filename = request.getParameter("filename");
        if (filename != null) {
            try {
                filename = new String(filename.getBytes("iso-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                // 处理异常
            }
        }
        if (filename == null){
            List<FilePojo> filePojoList = fileService.getAll();
            Integer code = filePojoList != null ? Code.GET_OK : Code.GET_ERR;
            String msg = filePojoList != null ? "" : "数据查询失败，请重试！";
            return new Result(code,filePojoList,msg);
        }
            List<FilePojo> filePojoList = fileService.selectAllFiles(filename);

        Integer code = filePojoList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = filePojoList != null ? "" : "数据查询失败，请重试！";
        return new Result(code,filePojoList,msg);
    }
}
